package com.example.demo.controller;

import com.example.demo.entity.ResponseEntity;
import com.example.demo.service.IElasticSearchService;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

@RestController
public class ElasticSearchController {


  @Autowired
  private IElasticSearchService iElasticSearchService;

  @PutMapping("/createIndexSettings")
  public void createIndexSettings(@RequestParam(name = "index") String index,
                                  @RequestParam(name = "shardsNum", defaultValue = "5") Integer shardsNum,
                                  @RequestParam(name = "replicasNum", defaultValue = "1") Integer replicasNum) {
    String result = null;

    try {
      result = iElasticSearchService.createIndexSettings(index, shardsNum, replicasNum);
      System.out.println("result：" + result);
    } catch (Exception e) {
      e.printStackTrace();

    }
  }

  @PutMapping("/updateIndexSettings")
  public void updateIndexSettings(@RequestParam(name = "index") String index,
                                  @RequestParam(name = "replicasNum", defaultValue = "") Integer replicasNum) {
    String result = null;

    try {
      result = iElasticSearchService.updateIndexSettings(index, replicasNum);
    } catch (Exception e) {
      e.printStackTrace();

    }
  }


  @DeleteMapping("/deleteIndex")
  public void deleteIndex(@RequestParam(name = "index") String index) {
    try {
      iElasticSearchService.deleteIndex(index);

    } catch (Exception e) {
      e.printStackTrace();

    }
  }

  @GetMapping("/getIndexSettings")
  public Map<String, Object> getIndexSettings(@RequestParam(name = "index", defaultValue = "resource") String index,
                                              @RequestParam(name = "type", defaultValue = "resource") String type) {
    try {

      Map<String, Object> result = iElasticSearchService.getIndexSettings(index, type);
      return result;

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

}
